package com.xinqi.modules.sys.dict.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xinqi.common.base.error.CommonErrors;
import com.xinqi.common.base.response.PageInfo;
import com.xinqi.common.base.response.Param;
import com.xinqi.common.mybatis.utils.Pages;
import com.xinqi.common.mybatis.utils.Queries;
import com.xinqi.modules.sys.dict.convert.DictGradeConvert;
import com.xinqi.modules.sys.dict.convert.DictStageConvert;
import com.xinqi.modules.sys.dict.domain.DictGradeEntity;
import com.xinqi.modules.sys.dict.domain.DictStageEntity;
import com.xinqi.modules.sys.dict.dto.req.AddGradeDTO;
import com.xinqi.modules.sys.dict.dto.req.DictStageCreateDTO;
import com.xinqi.modules.sys.dict.dto.req.DictStageDeleteDTO;
import com.xinqi.modules.sys.dict.dto.req.DictStageQueryDTO;
import com.xinqi.modules.sys.dict.dto.req.DictStageUpdateDTO;
import com.xinqi.modules.sys.dict.dto.rsp.DictGradeResultDTO;
import com.xinqi.modules.sys.dict.dto.rsp.DictStageResultDTO;
import com.xinqi.modules.sys.dict.manager.DictGradeManager;
import com.xinqi.modules.sys.dict.manager.DictStageGradeManager;
import com.xinqi.modules.sys.dict.manager.DictStageManager;
import com.xinqi.modules.sys.dict.service.DictStageService;
import com.xinqi.modules.sys.textbook.manager.CloudTextbookInfoManager;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.validation.Valid;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 字典-学段服务层实现
 *
 * @author: linkai
 * @date: 2023/05/03
 */
@Validated
@Service("dictStageService")
@RequiredArgsConstructor
public class DictStageServiceImpl implements DictStageService {
    private final DictStageConvert dictStageConvert;
    private final DictStageManager dictStageManager;

    private final DictGradeConvert dictGradeConvert;
    private final DictGradeManager dictGradeManager;

    private final DictStageGradeManager dictStageGradeManager;

    private final CloudTextbookInfoManager cloudTextbookInfoManager;

    /**
     * 分页查询 字典-学段数据
     */
    @Override
    @DS("slaver")
    public PageInfo<DictStageResultDTO> page(Param pageable, DictStageQueryDTO query) {
        IPage<DictStageEntity> page = dictStageManager.page(Pages.page(pageable), wrapper(query));
        return Pages.convert(page, dictStageConvert::convert);
    }

    /**
     * 查询 字典-学段数据
     */
    @Override
    public List<DictStageResultDTO> find(DictStageQueryDTO query) {
        return dictStageManager.list(wrapper(query)).stream()
            .map(dictStageConvert::convert).collect(Collectors.toList());
    }

    private LambdaQueryWrapper<DictStageEntity> wrapper(DictStageQueryDTO query) {
        LambdaQueryWrapper<DictStageEntity> wrapper = Queries.lambda();
        Queries.accept(query.getId(), v -> wrapper.eq(DictStageEntity::getId, v));
        Queries.accept(query.getName(), v -> wrapper.like(DictStageEntity::getName, v));
        wrapper.orderByAsc(DictStageEntity::getSort);
        return wrapper;
    }

    /**
     * 根据id查询 字典-学段数据
     */
    @DS("slaver")
    @Override
    public DictStageResultDTO findById(Long id) {
        CommonErrors.BAD_REQUEST.check(Objects.nonNull(id), "ID不能为空");
        return Optional.ofNullable(dictStageManager.findById(id)).map(s -> {
            DictStageResultDTO convert = dictStageConvert.convert(s);
            convert.setGradeList(dictStageGradeManager.findGradeByStageId(id));
            return convert;
        }).orElse(null);
    }

    /**
     * 新增 字典-学段数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long insert(@Valid DictStageCreateDTO dto) {
        DictStageEntity entity = dictStageConvert.create(dto);
        dictStageManager.save(entity);
        dictStageGradeManager.addGrade(entity.getId(), dto.getGradeIdList());
        return entity.getId();
    }

    /**
     * 根据id修改 字典-学段数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateById(@Valid DictStageUpdateDTO dto) {
        Optional.ofNullable(dictStageManager.getById(dto.getId()))
            .orElseThrow(() -> CommonErrors.BAD_REQUEST.asException("数据不存在"));
        DictStageEntity entity = dictStageConvert.update(dto);
        dictStageGradeManager.addGrade(entity.getId(), dto.getGradeIdList());
        return dictStageManager.updateById(entity);
    }

    /**
     * 根据id删除 字典-学段数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteById(Long id) {
        CommonErrors.BAD_REQUEST.check(Objects.nonNull(id), "ID不能为空");
        // 删除关联的年级
        dictStageGradeManager.delGrade(id);
        return dictStageManager.removeById(id);
    }

    /**
     * 根据id删除 字典-学段数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteById(DictStageDeleteDTO dto) {
        return deleteById(dto.getId());
    }

    /**
     * 根据学段ID 查询绑定的年级
     */
    @DS("slaver")
    @Override
    public List<DictGradeResultDTO> findGradeByStageId(Long id) {
        return dictStageGradeManager.findGradeByStageId(id);
    }

    /**
     * 根据学段ID 查询云课本绑定的年级
     */
    @DS("slaver")
    @Override
    public List<DictGradeResultDTO> findBindGradeByStageId(Long id) {
        List<Long> ids = cloudTextbookInfoManager.findByVersionIdList(id);
        LambdaQueryWrapper<DictGradeEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(DictGradeEntity::getId, ids);
        List<DictGradeEntity> list = dictGradeManager.list(wrapper);
        return dictGradeConvert.convert(list);
    }

    @DS("slaver")
    @Override
    public List<DictGradeResultDTO> findGradeByVersionId(Long versionId) {
        return dictStageGradeManager.findGradeByVersionId(versionId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean addGrade(@Valid AddGradeDTO dto) {
        return dictStageGradeManager.addGrade(dto.getStageId(), dto.getGradeIdList());
    }

    @Override
    public Boolean isExistName(String name, Long oId) {
        CommonErrors.BAD_REQUEST.check(StringUtils.isNotEmpty(name), "名称不能为空");
        return dictStageManager.isExistName(name, oId);
    }

}
